/**
 * Blob到ArrayBuffer转换Worker
 * 用于在后台线程中批量将Blob转换为ArrayBuffer
 */

import { CommandResponse, BatchTask, BatchTaskResult } from '../thread-pool';
import { readBlobAsArrayBuffer } from '../../fs/helpers';

// 监听主线程消息
self.onmessage = async (e) => {
  const { type } = e.data;
  if (type === CommandResponse.Command_BatchTask) {
    const { batchId, tasks }: BatchTask<{ blob: Blob, index: number }> = e.data;
    // 收集所有需要转移的ArrayBuffer
    const transferList: ArrayBuffer[] = [];
    try {
      // 处理所有批量任务
      const results = [];
      for (const task of tasks) {
        const { blob, index } = task.data;
        try {
          const arrayBuffer = await readBlobAsArrayBuffer({ blob });
          transferList.push(arrayBuffer);
          results.push({
            taskId: task.id,
            success: true,
            data: {
              index,
              arrayBuffer
            }
          });
        } catch (error) {
          results.push({
            taskId: task.id,
            success: false,
            error: error instanceof Error ? error.message : String(error)
          });
        }
      }

      // 发送批量任务完成响应，并转移ArrayBuffer所有权
      self.postMessage({
        type: CommandResponse.Response_BatchTaskComplete,
        batchId,
        results
      } as BatchTaskResult<{ arrayBuffer: ArrayBuffer, index: number }>, { transfer: transferList });
    } catch (error) {
      // 发送批量任务错误响应
      self.postMessage({
        type: CommandResponse.Response_Error,
        error: error instanceof Error ? error.message : String(error)
      });
    }
  }
}